package com.opencee.cloud.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.opencee.boot.db.mybatis.service.impl.SupperServiceImpl;
import com.opencee.cloud.base.entity.BaseAuthenticationDeviceEntity;
import com.opencee.cloud.base.mapper.BaseAuthenticationDeviceMapper;
import com.opencee.cloud.base.service.IBaseAuthenticationDeviceService;
import com.opencee.cloud.base.service.IpRegionService;
import com.opencee.cloud.uaa.dto.AuthenticationLogsDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author liuyadu
 */
@Slf4j
@Service
public class BaseAuthenticationDeviceServiceImpl extends SupperServiceImpl<BaseAuthenticationDeviceMapper, BaseAuthenticationDeviceEntity> implements IBaseAuthenticationDeviceService {

    @Autowired
    private IpRegionService ipRegionService;

    /**
     * 获取设备
     *
     * @param userId
     * @param deviceBrand
     * @param deviceModel
     * @param ip
     * @return
     */
    @Override
    public BaseAuthenticationDeviceEntity getBy(Long userId, String deviceBrand, String deviceModel, String ip) {
        QueryWrapper<BaseAuthenticationDeviceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BaseAuthenticationDeviceEntity::getUserId, userId)
                .eq(BaseAuthenticationDeviceEntity::getDeviceBrand, deviceBrand)
                .eq(BaseAuthenticationDeviceEntity::getDeviceModel, deviceModel)
                .eq(BaseAuthenticationDeviceEntity::getIp, ip);
        return getOne(queryWrapper);
    }

    /**
     * 添加日志
     *
     * @param dto
     * @return
     */
    @Override
    public void addDevice(AuthenticationLogsDTO dto) {
        BaseAuthenticationDeviceEntity entity = getBy(dto.getUserId(), dto.getDeviceBrand(), dto.getDeviceModel(), dto.getIp());
        // 解析ip
        String region = ipRegionService.getRegion(dto.getIp());
        String country = null;
        String province = null;
        String city = null;
        if (StringUtils.hasText(region)) {
            String[] arr = region.split(",");
            if (arr.length > 3) {
                country = arr[0];
                province = arr[1];
                city = arr[2];
            }
        }
        if (entity == null) {
            entity = new BaseAuthenticationDeviceEntity();
            BeanUtils.copyProperties(dto, entity);
            entity.setCountry(country);
            entity.setProvince(province);
            entity.setCity(city);
            save(entity);
        } else {
            BeanUtils.copyProperties(dto, entity);
            entity.setCountry(country);
            entity.setProvince(province);
            entity.setCity(city);
            updateById(entity);
        }
    }
}
